package com.ctsi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.core.common.util.$;
import com.ctsi.system.dto.RoleDsReqDTO;
import com.ctsi.system.entity.RoleDataScope;
import com.ctsi.system.mapper.RoleDataScopeMapper;
import com.ctsi.system.service.IRoleDataScopeService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色数据范围表 服务实现类
 * </p>
 *
 * @author wang xiao xiang
 */
@Service
public class RoleDataScopeServiceImpl extends ServiceImpl<RoleDataScopeMapper, RoleDataScope> implements IRoleDataScopeService {

	@Override
	public IPage<RoleDataScope> listPage(Page page, Search search) {
		LambdaQueryWrapper<RoleDataScope> queryWrapper = new LambdaQueryWrapper<>();
		return this.baseMapper.selectPage(page, queryWrapper);
	}

	@Override
	public List<String> getRoleDataScope(List<Long> roleIds) {
		//　查询列表
		List<RoleDataScope> roleDataScopes = this.list(Wrappers.<RoleDataScope>lambdaQuery().in(RoleDataScope::getRoleId, roleIds));
		// 返回Long列表
		return roleDataScopes.stream().map(roleDataScope -> $.toStr(roleDataScope.getOrgId())).collect(Collectors.toList());

	}

	@Override
	public boolean setDataScope(RoleDsReqDTO roleDsReq) {
		// 先删除数据
		this.remove(Wrappers.<RoleDataScope>lambdaQuery().eq(RoleDataScope::getRoleId, roleDsReq.getId()));
		// 再插入数据
		roleDsReq.getOrgIdList().forEach(orgId -> this.save(new RoleDataScope().setRoleId(roleDsReq.getId()).setOrgId(orgId)));
		return Boolean.TRUE;
	}
}
